﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Builders;
using MongoDB.Driver;

namespace duanzhi.web.Areas.m.Controllers
{
    using Models;
    using publicLibrary;
    public class aController : Controller
    {
        //
        // GET: /r/

        public ActionResult Index(string key = "", int pageIndex = 0, int pageSize = 12)
        {
            DataSession<MongoDataContext, article> db = new DataSession<MongoDataContext, article>();
            DataSession<MongoDataContext, tag> dbtag = new DataSession<MongoDataContext, tag>();
            IQueryable<article> aes = null;
            if (!string.IsNullOrWhiteSpace(key))
            {
                aes = db.Where("tags", key);
            }
            else
            {
                aes = db.query;
            }
            ViewData.Model = aes.OrderByDescending(d => d.datetime).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            ViewBag.tags = dbtag.query;
            ViewBag.pageNav = new pageNav() { pageCount = aes.Count(), pageSize = pageSize, pageIndex = pageIndex };
            return View();
        }


        //增加段子
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AA(FormCollection fc)
        {
            string c = fc["content"];
            string t = fc["title"];
            string un = fc["userName"].Trim();
            string id = fc["aID"];

            if (t.Trim() == "" && c.Trim() == "")
            {
                return RedirectToAction("index");
            }
            //外部图片处理：匹配aaaaa<img ....src="XXXXXX.XXX".../> 并输出XXXXX.XXX
            Regex reg = new Regex("(?i)(?<=\\<img.*?src=\\\")http://.*?(?=\\\")");

            var regs = reg.Matches(c);

            for (int x = 0; x < regs.Count; x++)
            {
                string str = regs[x].Value;
                string extName = Path.GetExtension(str).ToLower();
                if (extName == ".jpg" || extName == ".jpeg" || extName == ".gif")
                {
                    WebClient wc = new WebClient();
                    string dirPath = "/upload/" + "res/" + DateTime.Now.Year + "-" + DateTime.Now.Month;

                    string newFileName = dirPath + "/" + DateTime.Now.ToFileTime() + str.Substring(str.LastIndexOf("."), str.Length - str.LastIndexOf("."));

                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(Server.MapPath(dirPath));
                    }

                    string _nfn = Server.MapPath(newFileName);
                    wc.DownloadFile(str, _nfn);
                    c = c.Replace(str, newFileName);
                }

            };

            //内部tem图片移动到正式图片目录
            Regex regtem = new Regex("(?i)(?<=\\<img.*?src=\\\")/content/upload/temRes/.*?(?=\\\")");
            var regtems = regtem.Matches(c);
            for (int x = 0; x < regtems.Count; x++)
            {
                string str = regtems[x].Value;
                string extName = Path.GetExtension(str).ToLower();
                if (extName == ".jpg" || extName == ".jpeg" || extName == ".gif")
                {
                    WebClient wc = new WebClient();
                    string dirPath = "/content/upload/" + "res/" + DateTime.Now.Year + "-" + DateTime.Now.Month;

                    FileInfo f = new FileInfo(Server.MapPath(str));
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(Server.MapPath(dirPath));
                    }
                    f.MoveTo(Server.MapPath(dirPath + "/" + Path.GetFileName(str)));
                    c = c.Replace(str, dirPath + "/" + Path.GetFileName(str));
                }
            };



            article a = new article();
            a.datetime = DateTime.Now;
            a.lastDatetime = a.datetime;

            TryUpdateModel(a);
            a.content = c;
            //用户处理
            if (fc["userID"] == "")
            {
                a.userID = user.guest.Id;
                if (un == "")
                {
                    a.userName = user.login.name;
                }
                else
                {
                    a.userName = un;
                }
            }
            else
            {
                a.userID = user.guest.Id;
                a.userName = un;
            }

            DataSession<MongoDataContext, article> db = new DataSession<MongoDataContext, article>();


            //标签处理
            string tagsStr = fc["tagsStr"].Trim();
            if (!string.IsNullOrWhiteSpace(tagsStr))
            {
                var tagStrs = tagsStr.Replace("，", ",").Split(',');

                DataSession<MongoDataContext, tag> dbtag = new DataSession<MongoDataContext, tag>();
                foreach (var name in tagStrs)
                {
                    var tag = dbtag.query.FirstOrDefault(d => d.name == name);
                    if (tag == null)
                    {
                        tag = new tag() { name = name };
                        dbtag.Add(new tag() { name = name });
                    }
                    if (a.tags == null)
                    {
                        a.tags = new List<string>();
                    }
                    a.tags.Add(tag.name);
                }


            }
            //保持
            db.Save(a);
            return RedirectToAction("index");

        }

        //增加回复 ajax
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AR(string userName = "", string userID = "", string replyContent = "", string aID = "")
        {

            userName = userName.Trim();
            replyContent = replyContent.Trim();
            if (string.IsNullOrWhiteSpace(userName)) { userName = user.guest.name; }
            if (string.IsNullOrWhiteSpace(replyContent))
            {
                return myJsonResult.error("无内容");
            }

            try
            {
                DataSession<MongoDataContext, article> db = new DataSession<MongoDataContext, article>();
                var a = db.GetById(aID.toOId());
                if (a == null) { return myJsonResult.error("没找到回复目标"); }
                if (a.reply == null)
                {
                    a.reply = new List<reply>();
                }
                var r = new reply() { userID = user.guest.Id, userName = userName, content = replyContent };
                a.reply.Add(r);
                db.Save(a);
                return myJsonResult.success(r);
            }
            catch
            {
                return myJsonResult.error("出错");
            }



        }
        //表单copy图片临时上传 for imagePaster插件
        [HttpPost]
        public ActionResult TP()
        {
            var f = Request.Files[0];
            myUpload mu = new myUpload();
            mu.myDirectory = "temRes/";

            string fileName = mu.imageSave(f, false, false);

            return Content("/" + mu.showPath + mu.myDirectory + fileName);

        }
        //图片上传 for ckeditor
        [HttpPost]
        public ActionResult TPCK()
        {
            var CKEditorFuncNum = Request["CKEditorFuncNum"];
            var f = Request.Files[0];
            myUpload mu = new myUpload();
            mu.myDirectory = "temRes/";

            string fileName = mu.imageSave(f, false, false);

            string str = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(";
            str += CKEditorFuncNum;
            str += ", '";
            str += "/" + mu.showPath + mu.myDirectory + fileName;
            str += "' , '";
            str += "";
            str += "');</script>";

            return Content(str);

        }
        //
        // GET: /r/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /r/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /r/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /r/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
